home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C & C++ Multimedia Cyber Classroom
/
C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso
/
cpphtp2
/
code.jar
/
code
/
ch21
/
fig21_16.txt
< prev
Wrap
Text File
|
1998-02-27
|
2KB
|
56 lines
1 // Fig. 21.16: fig21_16.cpp
2 // Using virtual base classes.
3 #include <iostream.h>
4
5 class Base {
6 public:
7 // implicit default constructor
8
9 virtual void print() const = 0; // pure virtual
10 };
11
12 class DerivedOne : virtual public Base {
13 public:
14 // implicit default constructor calls
15 // Base default constructor
16
17 // override print function
18 void print() const { cout << "DerivedOne\n"; }
19 };
20
21 class DerivedTwo : virtual public Base {
22 public:
23 // implicit default constructor calls
24 // Base default constructor
25
26 // override print function
27 void print() const { cout << "DerivedTwo\n"; }
28 };
29
30 class Multiple : public DerivedOne, public DerivedTwo {
31 public:
32 // implicit default constructor calls
33 // DerivedOne and DerivedTwo default constructors
34
35 // qualify which version of function print
36 void print() const { DerivedTwo::print(); }
37 };
38
39 int main()
40 {
41 Multiple both; // instantiate Multiple object
42 DerivedOne one; // instantiate DerivedOne object
43 DerivedTwo two; // instantiate DerivedTwo object
44
45 Base *array[ 3 ];
46 array[ 0 ] = &both;
47 array[ 1 ] = &one;
48 array[ 2 ] = &two;
49
50 // polymorphically invoke print
51 for ( int k = 0; k < 3; k++ )
52 array[ k ] -> print();
53
54 return 0;
55 }